<html>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<title>Section 4.4.&nbsp; Looping</title>
<link rel="STYLESHEET" type="text/css" href="images/style.css">
<link rel="STYLESHEET" type="text/css" href="images/docsafari.css">
<script type="text/javascript"><!--
google_ad_client = "pub-0203281046321155";
google_alternate_ad_url = "http://www.bookhtml.com/adbrite.htm";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel ="4867465545";
google_color_border = "FFFFFF";
google_color_link = "0000FF";
google_color_bg = "FFFFFF";
google_color_text = "000000";
google_color_url = "0000FF";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-4-SECT-3.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-4-SECT-5.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<br><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td valign="top"><a name="learnphpmysql-CHP-4-SECT-4"></a>
<h3 id="title-IDARHJJT" class="docSection1Title">4.4. Looping</h3>
<a name="IDX-CHP-4-0155"></a> 
<a name="IDX-CHP-4-0156"></a> 

<p class="docText">Now change the flow of your PHP program based on comparisons, but if you want to repeat a task until a comparison is <tt>FALSE</tt>, you will need to use looping. Each time the code in the loop executes, it is called an <span class="docEmphasis">iteration</span>. It's useful for many common tasks such as displaying the results of a query by looping through the returned rows. PHP provides the <tt>while,<a name="IDX-CHP-4-0157"></a> 
 for</tt>, and <tt>while . . . do</tt> constructs to perform loops.<a name="IDX-CHP-4-0158"></a> 
</p>
<p class="docText">Each of the loop constructs requires two basic pieces of information. First, when to stop looping is defined just like the comparison in an <tt>if</tt> statement. Second, the code to perform is also required and specified either on a single line or within curly braces. A logical error would be to omit the code in the loop, causing an infinite<a name="IDX-CHP-4-0159"></a> 
 loop.</p>
<p class="docText">The code is executed as long as the expression evaluates to <tt>trUE</tt>. To avoid an <span class="docEmphasis">infinite loop</span>, which would loop forever, your code should affect the expressions so that it becomes <tt>FALSE</tt>. When this happens, the loop stops, and execution continues with the next line of code, following the logical loop.</p>
<a name="learnphpmysql-CHP-4-SECT-4.1"></a>
<h4 id="title-IDAKJJJT" class="docSection2Title">4.4.1. while Loops</h4>
<p class="docText">The <tt>while</tt> loop takes the expression followed by the code to execute. <a class="docLink" href="#learnphpmysql-CHP-4-FIG-3">Figure 4-3</a> illustrates how a <tt>while</tt> loop processes.</p>
<a name="learnphpmysql-CHP-4-FIG-3"></a><p><center>
<h5 class="docFigureTitle">Figure 4-3. How a while loop executes</h5>
<img border="0" alt="" width="390" height="302" SRC="images/learnphpmysql_0403.jpg">
</center></P><br>
<p class="docText">The syntax is for a <tt>while</tt> loop is:</p>
<pre>
while (<tt><I>expression</I></tt>)
{
  <tt><i>code to
 execute</I></tt>;
}
</pre><br>

<p class="docText">An example is shown in <a class="docLink" href="#learnphpmysql-CHP-4-EX-14">Example 4-14</a>.</p>
<a name="learnphpmysql-CHP-4-EX-14"></a><h5 id="title-IDA2KJJT" class="docExampleTitle">Example 4-14. A sample while loop that counts to 10</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<pre>
&lt;?php
$num = 1;

while ($num &lt;= 10){
    print "Number is $num&lt;br /&gt;\n";
    $num++;
}

print 'Done.';
?&gt;
</pre><br>

</td></TR></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-4-EX-14">Example 4-14</a> produces:</p>
<pre>
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Done.
</pre><br>

<p class="docText">Before the loop begins, the variable <tt>$num</tt> is set to 1. This is called initializing a counter variable. Each time the code block executes, it increases the value in <tt>$num</tt> by 1 with the statement <tt>$num++;</tt>. After 10 iterations, the evaluation <tt>$num &lt;= 10</tt> becomes <tt>FALSE</tt> and the loop stops, which then prints <tt>Done.</tt>.</p>
<P><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><TR><td><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><td width="60" valign="top"><img src="images/warning_yellow.jpg" width="51" height="36" alt=""></td><TD valign="top">
<p class="docText">Be careful not to create an infinite loop. It has the undesirable effects of not returning your page and taking a lot of processing time on the web server.</p>
</TD></tr></table></TD></TR></table></P><br>

<a name="learnphpmysql-CHP-4-SECT-4.2"></a>
<h4 id="title-IDAFMJJT" class="docSection2Title">4.4.2. do . . . while Loops</h4>
<a name="IDX-CHP-4-0160"></a> 

<p class="docText">The <tt>do . . . while</tt> loop takes an expression such as a <tt>while</tt> statement but places it at the end. The syntax is:</p>
<pre>
do {
  <tt><i>code to execute</i></tt>;
} (<tt><i>expression</i></tt>);
</pre><br>

<p class="docText">This loop is useful when you want to execute the block of code once regardless of the value in the expression. For example, let's count to 10 with this loop, as in <a class="docLink" href="#learnphpmysql-CHP-4-EX-15">Example 4-15</a>.</p>
<a name="learnphpmysql-CHP-4-EX-15"></a><h5 id="title-IDAFNJJT" class="docExampleTitle">Example 4-15. Counting to 10 with do...while</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<a name="IDX-CHP-4-0161"></a> 

<pre>
&lt;?php

$num = 1;

do {
    echo "Number  is ".$num."&lt;br /&gt;";
    $num++;
} while ($num &lt;= 10);

echo "Done.";

?&gt;
</pre><br>

</td></TR></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-4-EX-15">Example 4-15</a> produces the same results as <a class="docLink" href="#learnphpmysql-CHP-4-EX-14">Example 4-14</a>; if you change the value of <tt>$num</tt> to 11, the loop processes differently.</p>
<pre>
&lt;?php

$num = 11;

do {
    echo $num;
    $num++;
} while ($num &lt;= 10);

?&gt;
</pre><BR>

<p class="docText">This produces:</p>
<pre>
11
</pre><br>

<p class="docText">The code in the loop displays 11 because the loop always executes at least once. Following the pass, <tt>while</tt> evaluates to <tt>FALSE</tt>, causing execution to drop out of the <tt>do . . . while</tt> loop.</p>

<a name="learnphpmysql-CHP-4-SECT-4.3"></a>
<H4 id="title-IDAROJJT" class="docSection2Title">4.4.3. for Loops</h4>
<a name="IDX-CHP-4-0162"></a> 
<a name="IDX-CHP-4-0163"></a> 

<p class="docText"><tt>for</tt> loops provide the same general functionality as <tt>while</tt> loops, but also provide for a predefined location for initializing and changing a counter value. Their syntax is:</p>
<pre>
for (<tt><I>initialization expression</i></tt>; <tt><i>test expression</I></tt>; <tt><i>modification expression</i></tt>){
  <tt><i>code that is executed</i></tt>;
}
</pre><BR>

<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-4-FIG-4">Figure 4-4</a> shows a flowchart for a <tt>for</tt> loop.</P>
<a name="learnphpmysql-CHP-4-FIG-4"></a><p><center>
<h5 class="docFigureTitle">Figure 4-4. How a for loop executes</h5>
<img border="0" alt="" width="498" height="486" SRC="images/learnphpmysql_0404.jpg">
</center></p><BR>
<p class="docText">An example <tt>for</tt> loop is:</p>
<pre>
&lt;?php
for ($num = 1; $num &lt;= 10; $num++) {
    print "Number is $num&lt;br /&gt;\n";
}
?&gt;
</pre><BR>

<p class="docText">This produces:</p>
<pre>
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
</pre><BR>

<p class="docText">When your PHP program process the <tt>for</tt> loop, the initialization portion is evaluated. For each iteration of the portion that increments, the counter executes, followed by a check to see whether you're done. The result is a much more compact and easy-to-read statement.</P>
<P><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><tr><td><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><td width="60" valign="top"><img src="images/tip_yellow.jpg" width="50" height="54" alt=""></td><td valign="top">
<p class="docText">When specifying your <tt>for</tt> loop, if you don't want to include one of the expressions, such as the initialization expression, you may omit it, but you must still include the separating semicolons (<tt>;</tt>). <a class="docLink" href="#learnphpmysql-CHP-4-EX-16">Example 4-16</a> shows the usage of a <tt>for</tt> loop without the initialization expression.</p>
</td></tr></table></td></tr></table></p><br>

<a name="learnphpmysql-CHP-4-SECT-4.4"></a>
<h4 id="title-IDANRJJT" class="docSection2Title">4.4.4. Breaking Out of a Loop</H4>
<a name="IDX-CHP-4-0164"></a> 
<a name="IDX-CHP-4-0165"></a> 

<p class="docText">PHP provides the equivalent of an emergency stop button for a loop: the <tt>break</tt> statement. Normally, the only way out of a loop is to satisfy the expression that determines when to stop the loop. If the code in the loop finds an error that makes continuing the loop pointless or impossible, you can break out of the loop by using the <tt>break</tt> statement. It's like getting your shoelace stuck in an escalator. It really doesn't make any sense for the escalator to keep going!</p>
<p class="docText">Possible problems you might encounter in a loop include running out of space when writing to a file or attempting to divide by zero. In <a class="docLink" href="#learnphpmysql-CHP-4-EX-16">Example 4-16</a>, we simulate what can happen if you divide based on an unknown entry initialized from a form submission (that could be a user-supplied value). If your user is malicious or just plain careless, she might enter a negative value where you are expecting a positive value (although this should be caught in your form validation process). In the code that is executed as part of the loop, the code checks to make sure <tt>$counter</tt> is not equal to zero. If it is, the code calls <tt>break</tt>.</p>
<a name="learnphpmysql-CHP-4-EX-16"></a><H5 id="title-IDAPSJJT" class="docExampleTitle">Example 4-16. Using break to avoid division by zero</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><td>

<pre>
&lt;?php

$counter = -3;

for (; $counter &lt; 10; $counter++){
    // Check for division by zero
    if ($counter == 0){
        echo "Stopping to avoid division by zero.";
        break;
    }

    echo "100/$counter&lt;br /&gt;";
}

?&gt;
</pre><br>

</td></TR></table></p>
<p class="docText">This displays:</p>
<pre>
100/-3
100/-2
100/-1
Stopping to avoid division by zero.
</pre><BR>

<p class="docText">Of course, there may be times when you don't want to just skip one execution of the loop code. The <tt>continue</tt><a name="IDX-CHP-4-0166"></a> 
 statement performs this for you.</p>

<a name="learnphpmysql-CHP-4-SECT-4.5"></a>
<h4 id="title-IDAGTJJT" class="docSection2Title">4.4.5. continue Statements</H4>
<a name="IDX-CHP-4-0167"></a> 

<p class="docText">You can use the <tt>continue</tt> statement to stop processing the current block of code in a loop and jump to the next iteration of the loop. It's different from <tt>break;</tt> in that it doesn't stop processing the loop entirely. You're basically skipping ahead to the next iteration. Make sure you are modifying your test variable before the <tt>continue</tt> statement, or an infinite loop is possible.</p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-4-EX-17">Example 4-17</a> shows the preceding example using <tt>continue</tt> instead of <tt>break</tt>.</p>
<a name="learnphpmysql-CHP-4-EX-17"></a><h5 id="title-IDAEUJJT" class="docExampleTitle">Example 4-17. Using continue instead of break</h5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><td>

<pre>
&lt;?php

$counter =- 3;

for (; $counter &lt; 10; $counter++){
    // Check for division by zero
    if ($counter == 0){
        echo "Skipping to avoid division by zero.&lt;br /&gt;";
        continue;
    }

    echo "100/$counter&lt;br /&gt;";
}

?&gt;
</pre><br>

</td></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-4-EX-17">Example 4-17</a> displays:</p>
<pre>
100/-3
100/-2
100/-1
Skipping to avoid division by zero.
100/1
100/2
100/3
100/4
100/5
100/6
100/7
100/8
100/9
</pre><BR>

<p class="docText">Notice that the loop skipped over the <tt>$counter</tt> value of zero but continued with the next value.</p>
<p class="docText">We've now covered all of the major program flow language constructs. We've discussed the building blocks for controlling program flow in your programs. Expressions can be as simple as <tt>TRUE</tt> or <tt>FALSE</tt> and as complex as relational comparison with logical operators. The expressions combined with program flow control constructs like the <tt>if</tt> statement and <tt>switch</tt> make decision making easy.</P>
<p class="docText">We also discussed <tt>while, while . . . do</tt>, and <tt>for</tt> loops. Loops are very useful for common dynamic web page tasks such as displaying the results from a query in an HTML table.</P>


</TD></TR></table>
<br>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-4-SECT-3.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-4-SECT-5.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
</body></html>
